< previous page page_521 next page >

Page 521
Type.gifListing 13.14. Creating a foreign key relationship on unmatched field names.
//
// sqlvb04.sqv - Test CONSTRAINT SQL keyword
//
// create a database
dbMake sqlvb04.mdb;
// create jobs title table
CREATE TABLE JobsTable
   (JobTitle TEXT (20) CONSTRAINT PKJobTitle PRIMARY KEY,
    BudgetPrefix TEXT(5),
    BudgetCode   TEXT(10),
    BudgetSuffix TEXT(5),
    JobDesc MEMO,
    CONSTRAINT UKBudget UNIQUE (BudgetPrefix,BudgetCode,BudgetSuffix)
   );
// create job pay grade table
CREATE TABLE PayGrades
   (GradeID  TEXT(5)  CONSTRAINT PKGradeID PRIMARY KEY,
    JobName  TEXT(20) CONSTRAINT FKJobName REFERENCES JobsTable(JobTitle),
    PayMin   CURRENCY,
    PayMax   CURRENCY
   );

// create a test table to work with
CREATE TABLE EmpsTable
  (EmployeeID  TEXT(10) CONSTRAINT PKEmployeeID PRIMARY KEY,
   LastName    TEXT(30),
   FirstName   TEXT(30),
   LoginName   TEXT(15),
   JobTitle    TEXT(20) CONSTRAINT FKJobTitle REFERENCES JobsTable(JobTitle),
   Department  TEXT(10)
   );
// show empty table
SELECT * FROM JobsTable;
SELECT * FROM PayGrades;
SELECT * FROM EmpsTable;
// eof
Notice that the column PayGrades.JobName does not have the same name as its referenced column (JobsTable.JobTitle). You can still define a foreign key relationship for these columns. This relationship operates exactly the same as the one defined for EmpsTable.JobTitle and JobsTable.JobTitle.
It is also important to point out the order in which you must create tables when you are establishing foreign key constraints. You must always create the referenced table before you refer to it in a CONSTRAINT clause. Failure to adhere to this rule results in a database error when you run your SQL-VB5 script. SQL must see that the table exists before a foreign key reference to it can be established.

 
< previous page page_521 next page >

If you like this book, buy it!